// https://blog.51cto.com/u_13961087/5665853
export async function copyText(text: string) {
  const permission = await navigator.permissions.query({name: 'clipboard-write'} as any);
  if (permission.state === 'denied') {
    return console.error("Damn, we don't have permissions to do this")
  }
  try {
    await navigator.clipboard.writeText(text) // 写入文本
    console.log("done!")
  } catch (e: any) {
    console.error("Error while copying text!")
    console.error(e.message)
  }
}

async function copyImg() {
  const type = "image/png";

  let myImg = document.getElementById("myImage")

  let img = await fetch(myImg.getAttribute("src"))

  var blob = new Blob([await img.blob()], {type});
  var data = [new ClipboardItem({[type]: blob})];

  try {
    await navigator.clipboard.write(data)
    console.log("The image was copied")
  } catch (e) {
    console.error("There was a problem copying the imagge")
    console.error(e)
  }
}

async function pasteImage() {
  const destinationImage = document.getElementById("myImage") as HTMLImageElement;
  if (destinationImage == null) {
    throw new Error('image not found!.');
  }
  const permission = await navigator.permissions.query({name: 'clipboard-read'} as any);
  if (permission.state === 'denied') {
    throw new Error('Not allowed to read clipboard.');
  }
  const clipboardContents = await navigator.clipboard.read();
  for (const item of clipboardContents) {
    if (!item.types.includes('image/png')) {
      throw new Error('Clipboard contains non-image data.');
    }
    const blob = await item.getType('image/png');
    destinationImage.src = URL.createObjectURL(blob);
  }
}
